import json
from collections import OrderedDict

data = {
'name' : 'ACME',
'shares' : 100,
'price' : 542.23
}

json_str = json.dumps(data)
print('type:', type(json_str))
print(json_str)
print(json.dumps(data, indent = 4))

print('\n=====================\n')

data2 = json.loads(json_str)
print('type:', type(data2))
print(data2)


with open('data.json', 'w') as f:
    json.dump(data, f)

with open('data.json', 'r') as f:
    data = json.load(f)

# 一般来讲，JSON 解码会根据提供的数据创建 dicts 或 lists。
# 如果你想要创建其他类型的对象，可以给 json.loads() 传递 object_pairs_hook 或 object_hook 参数
s = '{"name": "ACME", "shares": 50, "price": 490.1}'
data = json.loads(s, object_pairs_hook = OrderedDict)
print(data)

class JSONObject:
    def __init__(self, d):
        self.__dict__ = d

data = json.loads(s, object_hook = JSONObject)
print(data)
print(data.name)


# 如果你想序列化对象实例，你可以提供一个函数，它的输入是一个实例，返回一个可序列化的字典
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

classes = {'Point' : Point}

def serialize_instance(obj):
    d = {'__classname__': type(obj).__name__}
    d.update(vars(obj))
    return d

def unserialize_object(d):
    clsname = d.pop('__classname__', None)
    if clsname:
        cls = classes[clsname]
        obj = cls.__new__(cls)
        for key, value in d.items():
            setattr(obj, key, value)
        return obj
    else:
        return d

p = Point(2, 3)
s = json.dumps(p, default = serialize_instance)
print(s)

a = json.loads(s, object_hook = unserialize_object)
print(a)
